package chap10collection.test8;


import java.util.HashSet;
import java.util.Set;

/**
 * @author zdl
 * @date 2024/12/17
 */
import java.util.*;

class Worker {
    String name;
    int age;
    //double salary; //改写为包装类
    Double salary;

    public Worker() {
    }

    public Worker(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
    //hashCode()方法重写错误     salary是double类型  hashCode的返回值是int类型，因此应改写salary类型为Double包装类，然后使用包装类的hashCode方法
    /*int hashCode(){
        return name.hashCode() + age + salary;
    }*/

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Worker worker = (Worker) o;
        return age == worker.age && Objects.equals(name, worker.name) && Objects.equals(salary, worker.salary);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, salary);
    }
}

public class Demo8 {
    /**
     * 在 Demo7基础上为 Worker 类增加相应的方
     * 法，使得 Worker 放入 HashSet 中时，Set 中没有重复元素。 并编写相应的测
     * 试代码。
     *
     *  方法思路:直接重写equal hashCode方法即可
     */
    public static void main(String[] args) {
        Set set = new HashSet();
        set.add(new Worker("“tom”", 18, 2000));
        set.add(new Worker("“tom”", 18, 2000));
        //set.add(0, new Worker("“jerry”", 18, 2000)); //HashSet 无序，不能使用下标
        System.out.println(set.size());  //1
    }
}
